package example.database;

import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;

import jssia.database.mysql.transactions.Transaction;
import jssia.database.mysql.transactions.TransactionManager;
import jssia.database.verification.Jssia;

import com.smoed.common.logging.Log;

import example.database.example.JssiaTestInnodbTable;
import example.database.preparedstatments.TestStatements;

public class ExamplUsage {

    public static void main(String[] args) {
        Jssia.verifySchema();

        try {
            Databases db = Databases.EXAMPLE;
            Connection conn = db.getConnection();
            insertTestRowTransaction.set(db.getConnection(), new BigDecimal("12.693"));
            final long id = TransactionManager.executeTransaction(conn, insertTestRowTransaction);

            ResultSet testResultSet= null;
            try {
                testResultSet = TestStatements.selectTestById(db.getConnection(), id);
                if (testResultSet.next()) {
                    BigDecimal bigDecimal = JssiaTestInnodbTable.DECIMAL_COL.get(testResultSet);
                    Log.info("Result: " + bigDecimal);

                    JssiaTestInnodbTable.DECIMAL_COL.update(testResultSet, new BigDecimal(4321.765));
                    testResultSet.updateRow();

                    bigDecimal = JssiaTestInnodbTable.DECIMAL_COL.get(testResultSet);
                    Log.info("Result: " + bigDecimal);
                }
            } finally {
                if (testResultSet != null) testResultSet.close();
            }

        } catch (SQLException e) {
            TransactionManager.printSQLException(e);
        }

    }

    private static final InsertTestRowTransaction insertTestRowTransaction = new InsertTestRowTransaction();
    private static class InsertTestRowTransaction implements Transaction<Long> {
        private Connection conn;
        private BigDecimal bigDecimal;

        private void set(Connection conn, BigDecimal bigDecimal) {
            this.conn = conn;
            this.bigDecimal = bigDecimal;
        }

        @Override public Long execute() throws SQLException {
            long id = 0;
            ResultSet autoKeyResultSet= null;
            try {
                autoKeyResultSet = TestStatements.insertTestRow(conn, bigDecimal);
                if (autoKeyResultSet.next())
                    id = JssiaTestInnodbTable.ID.get(autoKeyResultSet, 1);
            } finally {
                if (autoKeyResultSet != null) autoKeyResultSet.close();
            }

            return id;
        }

    }
}
